package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.model.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一token处理
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 进入controller方法前处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestMethod = request.getMethod();

        log.info("请求了路径: {}:{}",requestMethod, request.getRequestURI());
        if(handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if(null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }
        //1. 获取token
        String token = request.getHeader("Authorization");
        //1.1 有值处理
        if(StringUtils.isNotEmpty(token)) {
            // 【注意】从登录成功的代码中，token存入redis的使用的key
            String tokenKey = "TOKEN_" + token;
            // 通过tokenkey获取登录用户的信息 jsonString
            String userJsonString = stringRedisTemplate.opsForValue().get(tokenKey);
            // 有值
            if(StringUtils.isNotEmpty(userJsonString)){
                // 转成User对象
                User loginUser = JSON.parseObject(userJsonString, User.class);
                log.info("当前登录用户ID：" + loginUser.getId());
                //4. 存入ThreadLocal,
                UserHolder.setUser(loginUser);
                //放行 return true;
                return true;
            }
        }
        //5. 没有值, 401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }

}
